<template>
	<view>
		<pageHeader :leftImgBack='false' :fixed='true' @back='back' :border='true'>
			<text>发布艺术精品</text>
			<text slot="left" class="header-left" >取消</text>
		</pageHeader>
		<view class="body">
			<view class="message">
				<input type="text" placeholder="标题限20字以内（选填项）" v-model="title" placeholder-class="message_input" :maxlength='20'/>
			</view>
			<view class="message textarea">
				<textarea  placeholder="添加正文（选填项）" v-model="content" placeholder-class="message_input" :maxlength='-1'/>
			</view>
			<view class="addImg">
				<imgDele :src="item" mode="aspectFill" @imgTap='imgTap' :index='index' @deleSuccess='deleSuccess' v-for="(item,index) in imgPathList" :key='index'></imgDele>
				<view @tap="chooseImg">
					<image src="/static/svg/tianjia.svg" ></image>
				</view>
				<text v-if="imgPathList.length<=0">（至少添加一张图片）</text>
			</view>
			<productLink v-for='(item,index) in linkList' :key='index' :index='index' @toDele='toDeleProduct' :message='item'/>
			<image src="/static/svg/addLianjie.svg" v-if="linkList.length<10" class="addLianjie" @tap="toAddLianjie"></image>
		</view>
		<view class="button" :style="{borderColor:canDo?'#C84739':'#C8C8C8'}">
			<view @tap="toLook">
				<text :style="{color:canDo?'#C84739':'#C8C8C8'}">预览</text>
			</view>
			<view :style="{backgroundColor:canDo?'#C84739':'#C8C8C8'}" @tap="toAdd">
				<text>发布</text>
			</view>
		</view>
		<picturePreview :list='imgPathList' :index='imgIndex' v-if='showPreview'  @confirm='deleSuccess' @cancel='cancelPreview'/>
	</view>
</template>

<script>
	import urls from "@/common/util/homeArtIndex.js"
	import picturePreview from "@/components/picturePreview/picturePreview.vue"
	import pageHeader from "@/components/header/header.vue"
	import imgDele from "@/components/dele/imgDele.vue"
	import productLink from "@/components/ReleaseFineArt/productLink.vue"
	export default {
		components: {pageHeader,imgDele,productLink,picturePreview},
		data() {
			return {
				imgPathList:[],
				linkList:[
					// {
					// 	"shopLink":"421rrv12412v42",
					// 	"shopImage":"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3663179458,4263162468&fm=15&gp=0.jpg",   
					// 	"shopContent":"这是商品1号",  
					// 	"shopPrice":99.99,
					// },
					// {
					// 	"shopLink":"4v124v12c",
					// 	"shopImage":"https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3548804822,3650468119&fm=15&gp=0.jpg",
					// 	"shopContent":"这是商品1号",
					// 	"shopPrice":50.6,
					// },
				],
				title:"",
				content:"",
				canDo:false,
				showPreview:false,
				imgIndex:0,
				isEdit:false,
				id:""
			};
		},
		onLoad(e) {
			localStorage.removeItem('releaseFineArtMessage')
			if(e.isEdit){
				this.isEdit=true
				this.id=e.id
				this.getDraft()
			}
		},
		onShow(){
			this.getMessage()
		},
		onHide(){
			this.saveMessage()
		},
		methods: {
			async getDraft(){
				let res=await urls.editArtDraft({fineId:this.id})
				this.title=res.data.specific.fineTitle?res.data.specific.fineTitle:""
				this.content=res.data.specific.fineContent?res.data.specific.fineContent:""
				this.imgPathList=res.data.specific.fineImage?res.data.specific.fineImage.split(','):""
				if(this.imgPathList.length>0){
					this.canDo=true
				}
				this.linkList=res.data.shop?res.data.shop:[]
				this.saveMessage()
			},
			getMessage(){
				if(localStorage.getItem("releaseFineArtMessage")){
					let message=JSON.parse(localStorage.getItem("releaseFineArtMessage"))
					this.title=message.title?message.title:""
					this.content=message.content?message.content:""
					this.imgPathList=message.imgPathList?message.imgPathList:[]
					if(this.imgPathList.length>0){
						this.canDo=true
					}
					this.linkList=message.linkList?message.linkList:[]
				}
			},
			saveMessage(){
				let message={}
				message.title=this.title
				message.content=this.content
				message.imgPathList=this.imgPathList
				message.linkList=this.linkList
				localStorage.setItem('releaseFineArtMessage',JSON.stringify(message))
			},
			back(){
				if(this.title||this.content||this.imgPathList.length>0||this.linkList.length>0){
					uni.showModal({
						content: '是否保存草稿？',
						cancelText:'不保存',
						confirmText:'保存',
						success: async (res)=> {
						    if (res.confirm) {
								this.saveMessage()
								let message=JSON.parse(localStorage.getItem("releaseFineArtMessage"))
								let data={}
								data.fineTitle=message.title
								data.fineContent=message.content
								data.fineImage=message.imgPathList.join(',')
								data.userId=localStorage.getItem("userId")
								data.list=JSON.stringify(message.linkList)
								data.draft=0
								uni.showLoading({
									mask: true
								})
								let res
								if(this.isEdit){
									data.shopId=""
									data.fineId=this.id
									res=await urls.updatefineArt(data)
								}else{
									res=await urls.insertFineArt(data)
								}
								uni.hideLoading()
								if(res.code==0){
									uni.navigateBack({
										delta: 1
									})
								} 
						    } else if (res.cancel) {
						        uni.navigateBack({
						        	delta: 1
						        })
						    }
						}
					})
				}else{
					uni.navigateBack({
						delta: 1
					})
				}
			},
			async uploads(list){
			    const that=this     
			    let arr=[]
			    for (let k in list) {
			        arr[k]=await that.up_img(list[k])
			    } 
			    return arr;
			},
			up_img(url){ 
			    return new Promise((resolve, reject) => {  
			        uni.uploadFile({
			            url: 'http://classic.wljiam.com/caapi/card/insertreminder',
			            filePath: url,
			            name: 'file',
			            formData: {
			                'userId': localStorage.getItem("userId")
			            },
						success: (uploadFileRes) => { 
			                resolve(uploadFileRes.data);  
						}
					});
			    })  
			},
			chooseImg() {
				let count=9-this.imgPathList.length
				uni.chooseImage({
				    count: count, 
				    sizeType: ['compressed', 'original'],
				    sourceType: ['album', 'camera'],
				    success:async res=> {
						if(res.tempFilePaths.length>9||res.tempFilePaths.length+this.imgPathList.length>9||this.imgPathList.length+1>9){
							uni.showToast({
							    title: '最多上传9张图片',
								icon:'none',
							    duration: 1500
							})
							return
						}
						uni.showLoading({
						    title: '上传中...',
						})
						let arr=await this.uploads(res.tempFilePaths)	
						let tempFilePaths=[]
						for (let k in arr) {
							if(JSON.parse(arr[k]).code==0){
								 tempFilePaths[k]=JSON.parse(arr[k]).data
							}
						}
				        this.imgPathList.push(...tempFilePaths)
						uni.hideLoading()
						this.canDo=true
				    }
				})
			},
			imgTap(index){
				this.imgIndex=index
				this.showPreview=true
			},
			cancelPreview(){
				this.showPreview=false
			},
			deleSuccess(e){
				this.imgPathList.splice(e,1)
				if(this.imgPathList.length<=0){
					this.canDo=false
				}
			},
			toAddLianjie(){
				this.saveMessage()
				uni.navigateTo({
					url: '/pages/ReleaseFineArt/chooseProduct'
				})
			},
			toDeleProduct(index){
				this.linkList.splice(index,1)
			},
			toLook(){
				if(!this.canDo){
					return
				}
				this.saveMessage()
				if(this.isEdit){
					uni.navigateTo({
						url: '/pages/ReleaseFineArt/fineArtLook?isEdit=true&&id='+this.id
					})
				}else{
					uni.navigateTo({
						url: '/pages/ReleaseFineArt/fineArtLook'
					})
				}
			},
			async toAdd(){
				if(!this.canDo){
					return
				}
				this.saveMessage()
				let message=JSON.parse(localStorage.getItem("releaseFineArtMessage"))
				let data={}
				data.fineTitle=message.title
				data.fineContent=message.content?message.content:!message.title?"分享图片":""
				data.fineImage=message.imgPathList.join(',')
				data.userId=localStorage.getItem("userId")
				data.list=JSON.stringify(message.linkList)
				data.draft=1
				uni.showLoading({
					mask: true
				})
				let res
				if(this.isEdit){
					data.shopId=""
					data.fineId=this.id
					res=await urls.updatefineArt(data)
				}else{
					res=await urls.insertFineArt(data)
				}
				uni.hideLoading()
				if(res.code==0){
					localStorage.removeItem("releaseFineArtMessage")
					uni.showToast({
					    title: '发布成功',
					    duration: 1500
					})
					setTimeout(()=>{
						uni.navigateBack({
							delta: 1
						})
					},1500)
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
.header-left{
	font-size: 32rpx;
	letter-spacing: 1rpx;
	color: #666666;
}
.body{
	padding: 0 30rpx 128rpx;
	.message{
		height: 96rpx;
		border-bottom: 1rpx solid #EEEEEE;
		input{
			color: #333333;
			font-size: 32rpx;
			letter-spacing: 1rpx;
			height:95rpx ;
			width: 100%;
		}
		textarea{
			color: #333333;
			font-size: 28rpx;
			line-height: 36rpx;
			text-align: justify;
			letter-spacing: 1rpx;
			height:100% ;
			width: 100%;
		}
		.message_input{
			color: #999999;
		}
	}
	.textarea{
		height: 275rpx;
		padding: 30rpx 0;
	}
	.addImg{
		padding-bottom:30rpx;
		position: relative;
		display: flex;
		flex-wrap: wrap;
		border-bottom: 1rpx solid #EEEEEE;
		view{
			height: 210rpx;
			width: 210rpx;
			margin-top: 30rpx;
			margin-left: 30rpx;
			background-color: #FFFFFF;
			border-radius: 8rpx;
			/deep/ image{
				height: 100%;
				width: 100%;
				display: block;
				border-radius: 8rpx;
			}
		}
		text{
			position: absolute;
			bottom: 30rpx;
			left: 220rpx;
			font-size: 24rpx;
			letter-spacing: 1rpx;
			color: #333333;
		}
	}
	.addLianjie{
		height: 76rpx;
		width: 690rpx;
		display: block;
		margin-top: 30rpx;
	}
}
.addImg>view:nth-of-type(3n+1){
	margin-left: 0 !important;
}
.button{
	height: 98rpx;
	background-color: #FFFFFF;
	border-top: 1rpx solid #C84739;
	display: flex;
	position: fixed;
	width: 750rpx;
	bottom: 0;
	left: 0;
	view{
		height: 100%;
		width: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		text{
			color: #FFFFFF;
			font-size:34rpx ;
			letter-spacing: 1rpx;
			display: inline-block;
		}
	}
}
</style>
